# 引用包
library(limma)
library(GSVA)

# 定义文件路径
patientFile <- "/www/wwwroot/www.shenai.site/files/patientmatrix.csv"  # 表达数据文件
tjRCCFile <- "/www/wwwroot/www.shenai.site/files/tjRCC_TPM_finalversion.csv"
im2gene <- "/www/wwwroot/www.shenai.site/files/im2gene.csv"  # 免疫数据集文件
im4gene <- "/www/wwwroot/www.shenai.site/files/im4gene.csv"


# 单病人tpm表达矩阵处理，假定病人表达矩阵为一列基因，一列tpm
pati <- read.csv(patientFile, header = TRUE)
pati <- avereps(pati, ID = pati$gene_name)
rownames(pati) <- pati[,1]
pati <- pati[,-1, drop = FALSE]

# 合并内部数据与单病人数据
tjRCC <- read.csv(tjRCCFile, header = TRUE, row.names = "X")
tjRCC_tumor <- tjRCC[,grep("*T", colnames(tjRCC))]
data <- merge(pati, tjRCC_tumor, by = 'row.names', all = FALSE)
rownames(data) <- data$Row.names
data <- data[,-1]
dimnames <- list(rownames(data), colnames(data))
data <- matrix(as.numeric(as.matrix(data)), nrow = nrow(data), dimnames = dimnames)
data <- log2(data + 1)

# 读取免疫基因集文件
IM2score <- read.csv(file = im2gene)$x
IM4score <- read.csv(file = im4gene)$x
list <- list(IM2score = IM2score, IM4score = IM4score)

# 创建 ssGSEA 参数对象
param <- ssgseaParam(data, geneSets = list)

# 使用新的 API 进行 ssGSEA 分析
IM_ssgsea <- gsva(param, verbose = TRUE)

# 生成结果
# IM类型
imscore <- IM_ssgsea[2,1]-IM_ssgsea[1,1]
print(imscore)
IMsubtype <- ifelse(imscore < -0.2, "IM2", "IM4")
print(IMsubtype)

# 生成IM类型的简介
introduction <- ifelse(IMsubtype == "IM2",
                       "IM2",
                       "IM4")
print(introduction)

# 其他如生存分析、药敏.....
